<template>
    <div>
        <!-- 面包屑导航区域 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>用户管理</el-breadcrumb-item>
          <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 卡片试图区域 -->
        <el-card>
            <!-- 搜索框和添加添加按钮 -->
            <el-row :gutter="20">
                <el-col :span="8">
                    <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable v-on:clear="getUserList">
                        <el-button slot="append" icon="el-icon-search" v-on:click="getUserList"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" v-on:click='addUserVisible = true'>添加用户</el-button>
                </el-col>
            </el-row>

            <!-- 表格 -->
            <el-table :data="userList" border stripe>
              <el-table-column type="index"></el-table-column>
              <el-table-column prop="username" label="姓名"></el-table-column>
              <el-table-column prop="email" label="邮箱"></el-table-column>
              <el-table-column prop="mobile" label="电话"></el-table-column>
              <el-table-column prop="role_name" label="角色"></el-table-column>
              <el-table-column label="状态">
                  <template slot-scope="scope">
                      <el-switch v-model="scope.row.mg_state" v-on:change='userStatusChanged(scope.row)'></el-switch>
                  </template>
              </el-table-column>
              <el-table-column label="操作" width="180px">
                  <template slot-scope="scope">
                    <el-button size="mini" type="primary" icon="el-icon-edit" v-on:click="aditUserBtn(scope.row.id)"></el-button>
                    <el-button size="mini" type="danger" icon="el-icon-delete" v-on:click="removeUserById(scope.row.id)"></el-button>
                    <el-tooltip effect="dark" content="分配权限" placement="top" :enterable='false'>
                        <el-button size="mini" type="warning" icon="el-icon-setting"></el-button>
                    </el-tooltip>
                  </template>
              </el-table-column>
            </el-table>

            <!-- 分页 -->
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.pagenum" :page-sizes="[1,2,5,10]" :page-size="queryInfo.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
        </el-card>
    <!-- 添加用户的对话框 -->
    <el-dialog title="添加用户" :visible.sync="addUserVisible" width="50%" v-on:close="addUserClosed">
        <!-- 主体内容区域 -->
      <el-form :model="addUserForm" :rules="addUserFormRules" ref="addUserFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUserForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addUserVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户信息的对话框 -->
    <el-dialog title="修改用户信息" :visible.sync="editdialogVisible" width="50%" v-on:close="editClosed">
      <el-form :model="editFrom" :rules="editFromRules" ref="editFromRef" label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="editFrom.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editFrom.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editFrom.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        // 邮箱的自定义验证规则
        var checkEmail = (rule,value,cb) => {
            const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/

            if(regEmail.test(value)){
                // 合法的邮箱
                return cb()
            }
            cb(new Error('请输入合法的邮箱'))
        }

        // 手机的自定义验证规则
        var checkMobile = (rule,value,cb) => {
            const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/ 
            if(regMobile.test(value)){
                return cb()
            }
            cb(new Error('请输入合法的手机号'))
        }

        return {
            // 获取用户列表的参数对象
            queryInfo:{
                // 查询参数
                query:'',
                // 显示第几页
                pagenum:1,
                // 每页显示几条数据
                pagesize:2
            },
            // 用户列表数组
            userList:[],
            // 总条数
            total:0,
            // 控制添加用户对话框的显示与隐藏
            addUserVisible:false,
            // 添加用户的表单数据对象
            addUserForm:{
                username:'',
                password:'',
                email:'',
                mobile:''
            },
            // 添加用户表单的检验规则
            addUserFormRules:{
                username:[
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                ],
                password:[
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
                ],
                email:[
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    {validator:checkEmail,trigger: 'blur'}
                ],
                mobile:[
                    { required: true, message: '请输入手机号', trigger: 'blur' },
                    {validator:checkMobile,trigger: 'blur'}
                ]
            },
            // 控制修改用户信息对话框的显示与隐藏
            editdialogVisible: false,
            // 根据ID查询到的用户信息对象
            editFrom:{},
            // 修改用户信息的校验规则
            editFromRules:{
                email:[
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    {validator:checkEmail,trigger: 'blur'}
                ],
                mobile:[
                    { required: true, message: '请输入手机号', trigger: 'blur' },
                    {validator:checkMobile,trigger: 'blur'}
                ]
            },
            // 
        };
    },
    created() {
        // 获取首屏的用户数据
        this.getUserList()
    },
    mounted() {

    },
    methods: {
        // 获取用户列表数据
        getUserList: async function(){
            const {data:res} = await this.$http.get('users',{params:this.queryInfo})
            if(res.meta.status !== 200){
                return this.$message.error('获取用户列表失败！')
            }
            this.userList = res.data.users
            this.total = res.data.total
            

        },
        // 每页显示的条数发生变化，触发的函数
        handleSizeChange:function(newSize){
            this.queryInfo.pagesize = newSize
            this.getUserList()
        },
        // 页码值发生变化，触发的函数
        handleCurrentChange:function(newnum){
            this.queryInfo.pagenum = newnum
            this.getUserList()
        },
        // 监听switch开关的状态
        userStatusChanged: async function(userinfo){
            console.log(userinfo);
            const {data:res} =  await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
            if(res.meta.status !== 200){
                userinfo.mg_state = !userinfo.mg_state
                return this.$http.error('设置状态失败')
            }
            this.$message.success('设置状态成功')

        },
        // 监听添加用户的对话框的关闭，重置表单
        addUserClosed:function(){
            this.$refs.addUserFormRef.resetFields()
        },
        // 点击按钮，添加新用户 
        addUser:function(){
            // 首先要进行预校验
            this.$refs.addUserFormRef.validate( async valid =>{
                if(!valid){
                    return 
                }
                // 预校验通过以后，发起请求
                const {data:res} = await this.$http.post('users',this.addUserForm)
                
                if(res.meta.status !== 201){
                    return this.$message.error('用户创建失败！')
                }
                this.$message.success('用户创建成功！')
                // 隐藏对话框
                this.addUserVisible = false
                // 重新获取列表数据
                 this.getUserList()
            })
        },
        // 点击按钮，修改用户信息
        aditUserBtn: async function(id){
            const {data:res} = await this.$http.get('users/' + id)
            if(res.meta.status !== 200){
                return this.$message.error('查询失败！')
            }
            console.log(res);
            // 保存查询到的用户信息
            this.editFrom = res.data
            
            this.editdialogVisible = true
        },
        // 监听修改用户对话框，关闭重置表单
        editClosed:function(){
            this.$refs.editFromRef.resetFields()
        },
        // 修改用户信息，并提交
        editUserInfo:function(){
            // 预校验
            this.$refs.editFromRef.validate( async valid => {
                if(!valid) return
                // 通过预校验后，发起请求
                const {data:res} = await this.$http.put('users/' + this.editFrom.id,{
                    email:this.editFrom.email,
                    mobile:this.editFrom.mobile,
                })
                if(res.meta.status !== 200){
                    return this.$message.error('更新失败！')
                }
                // 关闭对话框
                this.editdialogVisible = false
                // 刷新列表
                this.getUserList()
                // 提示刷新成功
                this.$message.success('更新用户信息成功')
            })
        },
        // 根据id删除用户
        removeUserById: async function(id){
            // 弹出询问框
            const confirmResult =  await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err => err)
            if(confirmResult !== 'confirm'){
                return this.$message.info('取消删除')
            }
            // 确认删除
            const {data:res} = await this.$http.delete('users/' + id)

            if(res.meta.status !== 200){
                return this.$message.error('删除失败！')
            }
            this.$message.success('删除成功')
            if(this.total % this.queryInfo.pagesize === 1 && this.queryInfo.pagenum !== 1){
                this.queryInfo.pagenum--
                this.getUserList()
            }
            this.getUserList()
        }
    }
};
</script>

<style scoped lang="less">

</style>
